package com.viknix.threadpool.manager.cluster.util;

import com.viknix.threadpool.manager.cluster.constant.MemberMetaDataConstants;
import com.viknix.threadpool.manager.cluster.core.ServerMemberManager;
import com.viknix.threadpool.manager.cluster.enums.NodeState;
import com.viknix.threadpool.manager.cluster.core.Member;
import com.viknix.threadpool.manager.server.dependence.util.EnvUtil;
import com.viknix.threadpool.manager.server.dependence.util.ExceptionUtil;
import com.viknix.threadpool.manager.server.dependence.util.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author: Dongqi
 * @Date: 2021/11/10 19:28
 * @Version 1.0
 * @Description: Member node tool class.
 */
@Slf4j
public class MemberUtil {

    protected static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused";

    /**
     * 将 newMember 数据拷贝到 oldMember 上
     *
     * @param newMember {@link Member}
     * @param oldMember {@link Member}
     */
    public static void copy(Member newMember, Member oldMember) {
        oldMember.setIp(newMember.getIp());
        oldMember.setPort(newMember.getPort());
        oldMember.setState(newMember.getState());
        oldMember.setExtendInfo(newMember.getExtendInfo());
        oldMember.setAddress(newMember.getAddress());
    }

    /**
     * 解析出IP地址和端口号，并且构建 Member 对象
     *
     * @param member ip:port
     * @return {@link Member}
     */
    @SuppressWarnings("PMD.UndefineMagicConstantRule")
    public static Member singleParse(String member) {

        // Tpm 默认端口
        int defaultPort = 3180;

        String address = member;
        int port = defaultPort;
        // 对 ip:port 字符串进行切分
        String[] info = IPUtil.splitIPPortStr(address);
        if (info.length > 1) {
            address = info[0];
            port = Integer.parseInt(info[1]);
        }
        // 构建Member对象，状态为 UP
        Member target = Member.builder().ip(address).port(port).state(NodeState.UP).build();

        Map<String, Object> extendInfo = new HashMap<>(4);
        // Raft 默认端口为 : Member 端口 - 1000
        extendInfo.put(MemberMetaDataConstants.RAFT_PORT, String.valueOf(calculateRaftPort(target)));
        target.setExtendInfo(extendInfo);
        return target;
    }

    public static int calculateRaftPort(Member member) {
        return member.getPort() - 1000;
    }

    /**
     * Resolves to Member list.
     *
     * @param addresses ip list, example [127.0.0.1:8847,127.0.0.1:8848,127.0.0.1:8849]
     * @return member list
     */
    public static Collection<Member> multiParse(Collection<String> addresses) {
        List<Member> members = new ArrayList<>(addresses.size());
        for (String address : addresses) {
            Member member = singleParse(address);
            members.add(member);
        }
        return members;
    }

    /**
     * 成功处理节点上的操作。
     *
     * @param member {@link Member}
     */
    public static void onSuccess(final ServerMemberManager manager, final Member member) {
        final NodeState old = member.getState();
        manager.getMemberAddressInfos().add(member.getAddress());
        // 更新目标节点的状态为 UP
        member.setState(NodeState.UP);
        member.setFailAccessCnt(0);
        if (!Objects.equals(old, member.getState())) {
            manager.notifyMemberChange();
        }
    }

    public static void onFail(final ServerMemberManager manager, final Member member) {
        // 避免方法内部空指针，传入一个空信息异常
        onFail(manager, member, ExceptionUtil.NONE_EXCEPTION);
    }

    /**
     * 节点上操作的失败处理。
     *
     * @param member {@link Member}
     * @param ex     {@link Throwable}
     */
    public static void onFail(final ServerMemberManager manager, final Member member, Throwable ex) {
        // 将目标节点从健康节点列表中移除
        manager.getMemberAddressInfos().remove(member.getAddress());
        final NodeState old = member.getState();
        // 更新目标节点状态
        member.setState(NodeState.SUSPICIOUS);
        // 更新失败次数
        member.setFailAccessCnt(member.getFailAccessCnt() + 1);
        // 获取最大失败次数，默认为3次
        int maxFailAccessCnt = EnvUtil.getProperty("tpm.core.member.fail-access-cnt", Integer.class, 3);

        // 如果连续访问目标节点失败的次数达到了最大阈值，或者链接请求被拒绝，状态直接down
        if (member.getFailAccessCnt() > maxFailAccessCnt || StringUtils
                .containsIgnoreCase(ex.getMessage(), TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)) {
            member.setState(NodeState.DOWN);
        }
        // 如果节点状态发生改变，发布 MembersChangeEvent 事件
        if (!Objects.equals(old, member.getState())) {
            manager.notifyMemberChange();
        }
    }

    /**
     * 节点列表信息持久化。
     *
     * @param members member list
     */
    public static void syncToFile(Collection<Member> members) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("#").append(LocalDateTime.now()).append(StringUtils.LF);
            for (String member : simpleMembers(members)) {
                builder.append(member).append(StringUtils.LF);
            }
            EnvUtil.writeClusterConf(builder.toString());
        } catch (Throwable ex) {
            log.error("cluster member node persistence failed : {}", ExceptionUtil.getAllExceptionMsg(ex));
        }
    }

    /**
     * We randomly pick k nodes.
     *
     * @param members member list
     * @param filter  filter {@link Predicate}
     * @param k       node number
     * @return target members
     */
    @SuppressWarnings("PMD.UndefineMagicConstantRule")
    public static Collection<Member> kRandom(Collection<Member> members, Predicate<Member> filter, int k) {

        Set<Member> kMembers = new HashSet<>();

        // Here thinking similar consul gossip protocols random k node
        int totalSize = members.size();
        Member[] membersArray = members.toArray(new Member[totalSize]);
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        for (int i = 0; i < 3 * totalSize && kMembers.size() < k; i++) {
            int idx = threadLocalRandom.nextInt(totalSize);
            Member member = membersArray[idx];
            if (filter.test(member)) {
                kMembers.add(member);
            }
        }

        return kMembers;
    }

    /**
     * 将集群的节点信息分别封装成 Member 对象
     *
     * @param members 集群配置信息
     * @return 集群 Member 对象集合
     */
    public static Collection<Member> readServerConf(Collection<String> members) {
        Set<Member> nodes = new HashSet<>();

        for (String member : members) {
            Member target = singleParse(member);
            nodes.add(target);
        }
        return nodes;
    }

    /**
     * Select target members with filter.
     *
     * @param members original members
     * @param filter  filter
     * @return target members
     */
    public static Set<Member> selectTargetMembers(Collection<Member> members, Predicate<Member> filter) {
        return members.stream().filter(filter).collect(Collectors.toSet());
    }

    /**
     * 获取成员地址列表。
     *
     * @param members members
     * @return 地址列表
     */
    public static List<String> simpleMembers(Collection<Member> members) {
        return members.stream().map(Member::getAddress).sorted()
                .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
    }

    /**
     * 判断基本信息是否发生变化。
     *
     * @param actual   新的节点信息
     * @param expected 原来的节点信息
     * @return 如果基本信息有变化，则为true，否则为false
     */
    public static boolean isBasicInfoChanged(Member actual, Member expected) {
        if (null == expected) {
            return null == actual;
        }
        if (!expected.getIp().equals(actual.getIp())) {
            return true;
        }
        if (expected.getPort() != actual.getPort()) {
            return true;
        }
        if (!expected.getAddress().equals(actual.getAddress())) {
            return true;
        }
        if (!expected.getState().equals(actual.getState())) {
            return true;
        }
        return isBasicInfoChangedInExtendInfo(expected, actual);
    }

    /**
     * 比较扩展参数是否一致（raftPort、site、adWeight、weight、lastRefreshTime、version）
     *
     * @param expected 原来的节点信息
     * @param actual   新的节点信息
     * @return 如果信息有变化，则为true，否则为false
     */
    private static boolean isBasicInfoChangedInExtendInfo(Member expected, Member actual) {
        for (String each : MemberMetaDataConstants.BASIC_META_KEYS) {
            if (expected.getExtendInfo().containsKey(each) != actual.getExtendInfo().containsKey(each)) {
                return true;
            }
            if (!Objects.equals(expected.getExtendVal(each), actual.getExtendVal(each))) {
                return true;
            }
        }
        return false;
    }
}
